import { Component, OnInit, Input, Output, EventEmitter, ElementRef } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config } from '../smartadmin.config';
import { Router } from "@angular/router";

declare var $: any;
var pinyin = require("pinyin");
@Component({
	selector: 'sa-company-tree-car-btn',
	templateUrl: './companyTreeCarBtn.component.html',
	styleUrls: ['./companyTreeCarBtn.component.css'],
})
export class CompanyTreeCarBtnComponent implements OnInit {
	@Input() companyTreeId: string; //公司树标识Id
	@Input() wrap: any; //事件页面根元素Id
	@Input() companyData: any; //父组件公司数据
	@Input() Height: number; //高度
	@Input() inputName: string = 'companyName'; //校验使用的公司名称;默认name="companyName"
	@Input() placeholder: string = '请选择';//弱提示语
	@Input() opreateCarNumber:any ;//对车辆进行操作
	@Input() keyCodeEvent:boolean ;//对车辆进行操作
	@Input() noCar: boolean; // 条件为true 时不显示选择车辆
	@Input() preNext: boolean; // 条件为true 时可以上下选择车辆
	@Input() sourceCarUrl: string = 'stats/carListByCarNumber.html'; //默认 为全部车辆
	@Input() typeFlag: string = ''; //2问题分析处理;
	@Output() companySelected = new EventEmitter();
	isAllowPre: boolean = false;
	isAllowNext: boolean = false;
	selectIndex: any = '' // 选中的位置
	selectCount: any = '' // 选中的总数
	carList = [];
	carIndexMsg: any = {
		allNums: 0,
		index: 1,
		status: false,
	}
	companyName: string = ''; //选中的公司名称
	companyId: string = ''; //选中的公司ID
	deviceId: string = ''; //设备ID
	carNumber: string = ''; //车牌号码
	companyClickFlag:boolean = false;//组件公司选中点击标记
	carClickFlag:boolean = false;//组件车辆选中点击标记
	clearKeyCodeEvent:boolean = false;//清除父级键盘事件
	enterEventFlag:boolean = false;//组件enter监听
	clearTimer: any = '' // 定时器id
	constructor(private jsonApiService: JsonApiService, private el: ElementRef, private router: Router) {}
	//将时间传递给父组件
	sendParent() {
		let companyInfo = {
			'companyClickFlag':this.companyClickFlag,
			'carClickFlag':this.carClickFlag,
			'companyName': this.companyName,
			'companyId': this.companyId,
			'deviceId': this.deviceId,
			'carNumber': this.carNumber,
			'clearKeyCodeEvent':this.clearKeyCodeEvent,
			'enterEventFlag':this.enterEventFlag,
		}
		this.companySelected.emit(companyInfo);
	}
	ngOnInit() {
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				this.select2Car(); //初始化select 2 车辆
			});
			System.import('assets/js/jstree/jstree.min.js').then(() => {
				this.initCompanyList();
				this.companyCilckEvent();
			})
		});
	}
	//绑定键盘事件
	keyEvent(){
		document.onkeydown = null;
		document.body.onkeydown = null;
		document.onkeydown = function(event) {
			var e = event || window.event || arguments.callee.caller.arguments[0];
			if(e) {
				if(e.keyCode == 38) {
					this.nextCar('pre');
					return false;
				}
				if(e.keyCode == 40) {
					this.nextCar('next');
					return false;
				}
				if(e.keyCode == 13){
					this.enterEventFlag = true;
					this.sendParent();
					this.enterEventFlag = false;
					return false;
				}
			}
		}.bind(this)
	}
	ngOnChanges() {
	    let that = this;
	    if(this.companyData && this.companyData.companyId){
            this.companyName = this.companyData.companyName;
            this.companyId = this.companyData.companyId;
            setTimeout(()=>{
                that.queryCarListByCompanyId(this.companyData.companyId);
            },800);
            $('#' + this.companyTreeId).find('.tree_company_input').val(this.companyData.companyName).change();
        }
//      // 没有公司直接搜索车牌号选择然后进行查询的情况
        if(this.companyData && this.companyData.deviceId&&!this.companyData.companyId){
            this.deviceId = this.companyData.deviceId;
            this.carNumber = this.companyData.carNumber;
            var carOption = $("<option>");
            carOption.attr("value",this.companyData.deviceId);
            carOption.text(this.companyData.carNumber);
            $('#carNumberSelect2').append(carOption);
            $('#carNumberSelect2').val(this.companyData.deviceId).trigger('change');
            // 显示之后再将这条数据删除 不然再选择公司会存留数据
            this.companyData.deviceId="";
            this.companyData.carNumber="";
        }
		if(this.opreateCarNumber&& this.carNumber){
			this.carNumber = '';
			//采用简单粗暴的方法清除;官方推荐的方法失效
			var str = $("<span class='select2-selection__placeholder'>请选择</span>");
			$('#carNumberSelect2').val("");
			$("#select2-carNumberSelect2-container").empty();
			$("#select2-carNumberSelect2-container").attr("title", "");
			$("#select2-carNumberSelect2-container").prepend(str);
			this.opreateCarNumber = '';
			this.isAllowNext = false;
			this.isAllowPre = false;
			this.carIndexMsg.status = false;
			this.sendParent();
		}
		if(this.keyCodeEvent){
			document.onkeydown = null;
		}
		
	}
	//页面点击事件监听,显示隐藏弹窗
	companyCilckEvent() {
		let companyTreeM = document.getElementById(this.companyTreeId);
		let tree_box = companyTreeM.getElementsByClassName('s_tree_box')[0];
		let company = companyTreeM.getElementsByClassName('tree_company_input')[0];
		let wrap:any = this.wrap ? document.getElementsByTagName(this.wrap) : document;
		wrap.onclick = function(e: any) {
			if(tree_box.contains(e.target)||e.target == company){//判断点击是否在下拉框内
				if(e.target.className == 'jstree-anchor jstree-hovered jstree-clicked'||
					e.target.className == 'jstree-icon jstree-themeicon fa fa-home jstree-themeicon-custom'||
					e.target.className == 'jstree-anchor jstree-hovered jstree-clicked jstree-search')
				{
					tree_box.className = tree_box.className.replace("tree_open","");
				}
			}else{
				tree_box.className = tree_box.className.replace("tree_open","");
			}
		}
	}
	ngOnDestroy() {
		let wrap:any = this.wrap ? document.getElementsByTagName(this.wrap) : document;
		wrap.onclick = null;
	}
	//拉取公司数据,生成公司树
	initCompanyList() {
		var that = this;
		$('#' + this.companyTreeId).find('.treeId').eq(0).jstree({
			"core": {
				'data': function(obj, callback) {       
					var jsonstr = "[]";       
					var jsonarray = eval('(' + jsonstr + ')');
					var url = 'company/companytree.html';
					$.ajax({        
						type: "GET",
						url: config.BaseURL + url,
				        dataType: "json",
						xhrFields: {
							withCredentials: true
						},
						timeout : 30000,
				        success: function(result) {
							// 增加公司拼音字段
							var forData = result.data ? result.data : result;
							if (forData.length) {
								for(let i = 0; i < forData.length; i++) {
									forData[i].text = forData[i].text + `<span style="display: none;">${pinyin(forData[i].text,{style: pinyin.STYLE_NORMAL}).join('')}</span>`
								}
							}

							jsonarray = result;  
							callback.call(this, jsonarray);
						},
						error: function (data, errorMsg) {
						    if(data.statusText === 'timeout'){
                                    this.jsonApiService.message('请求超时,请重试')
                            }else{
                                common.clearCookie('isLogin');
                                common.clearCookie('WEBSIDE_SID');
                                localStorage.clear();
                                this.router.navigate(['/auth']);
                            }
                        }        
					});   
				},

				"themes": {
					"responsive": true
				},
				"multiple": false,
				"animation": 200,
				"dblclick_toggle": true,
				"expand_selected_onload": true
			},
			"plugins": ["search"]
		}).bind("activate_node.jstree", function(e, obj) {
			that.companyClickFlag = true;
			var currentNode = obj.node; // 获取当前节点   
			that.companyName = currentNode.text.substring(0, currentNode.text.indexOf('<')); // 获取内容前删除添加的拼音字段
			that.companyId = currentNode.id;
			$('#' + that.companyTreeId).find('.tree_company_input').val(that.companyName).change();
			that.queryCarListByCompanyId(currentNode.id);
			that.companySearch();
			that.sendParent();
			that.companyClickFlag = false;
			if($('#' + that.companyTreeId).find('.jstree-searchCheck').length > 0){
				if($('#' + that.companyTreeId).find('.jstree-searchCheck')[0].className == 'jstree-anchor jstree-search jstree-searchCheck' || 
				$('#' + that.companyTreeId).find('.jstree-searchCheck')[0].className == 'jstree-anchor jstree-searchCheck jstree-hovered jstree-clicked'){
					$('#' + that.companyTreeId).find('.s_tree_box')[0].className = "s_tree_box";
					that.selectIndex = '';
					that.selectCount = '';
				}
			}else{
				if(that.companyName){
					$('#' + that.companyTreeId).find('.s_tree_box')[0].className = "s_tree_box";
				}
			}
		})
	}

	//擦除公司所选值
	delText() {
		this.carIndexMsg.status = false;
		this.companyName = '';
		this.companyId = '';
		this.deviceId = '';
		this.carNumber = '';
		this.carList = [];
		this.clearSelect2($("#carNumberSelect2")); //清除Select中的数据
		this.select2Car();
		$('#' + this.companyTreeId).find('.treeSearchInput').val('');
		$('#' + this.companyTreeId).find('.tree_company_input').val("").change();
		this.companySearch();
		if($('#' + this.companyTreeId).find('.s_tree_box')[0].className.indexOf('tree_open') > 0) {
			$('#' + this.companyTreeId).find('.tree_company_input').focus();
		}
		this.selectIndex = '';
		this.selectCount = '';
		if($('#' + this.companyTreeId).find('.jstree-searchCheck').length != 0){
			$('#' + this.companyTreeId).find('.jstree-searchCheck')[0].className = "jstree-anchor"
		}
		this.sendParent()
	}
	//打开公司树
	companyClick() {
		$('#' + this.companyTreeId).find('.s_tree_box').toggleClass('tree_open');
		// this.selectIndex = '';
		// this.selectCount = '';
		// if($('#' + this.companyTreeId).find('.jstree-searchCheck').length != 0){
		// 	$('#' + this.companyTreeId).find('.jstree-searchCheck')[0].className = "jstree-anchor"
		// }
	}
	//公司树模糊搜索
	companySearch() {
		var that = this;
		var value = $('#' + this.companyTreeId).find('.treeSearchInput').val();

		that.selectIndex = '';
		that.selectCount = '';
		// for(var j=0;j<$('#' + this.companyTreeId).find('.jstree-anchor').length;j++){
		// 	$('#' + this.companyTreeId).find('.jstree-anchor')[j].className = "jstree-anchor";
		// }

		const oldSearchCheckElList = $('#' + this.companyTreeId).find('.jstree-searchCheck')
		if(oldSearchCheckElList.length > 0) {
		  for (var j = 0; j <oldSearchCheckElList.length; j++) {
			oldSearchCheckElList[j].className = 'jstree-anchor'
		  }
		}

		if(this.clearTimer) { clearTimeout(this.clearTimer); }
		this.clearTimer = setTimeout(function () {
			$('#' + that.companyTreeId).find('.treeId').eq(0).jstree(true).search(value);
			let searchResult = $('#' + that.companyTreeId).find('.jstree-search').length;
			if(searchResult < 1) {
				return;
			}

			if(value){
				that.selectIndex = 1;
				that.selectCount = $('#' + that.companyTreeId).find('.jstree-search').length;
				$('#' + that.companyTreeId).find('.jstree-search')[0].className = "jstree-anchor jstree-search jstree-searchCheck";
			}

			$('#' + that.companyTreeId).find('.jstree-search').each(function(index, obj) {
				if(index < 1) { //js树搜索定位到结果的第一个地方；
					let container = $('#' + that.companyTreeId).find('.vision_tree');
					let scrollTo = $(this);
					// container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
					container.animate({
						scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
					});
				}
			})
		},250)
	}
	upArrow(){
		var that = this;
		if(parseInt(this.selectIndex) == 1){
			that.jsonApiService.message("目前已经在开始位置");
			return;
		}
		that.selectIndex = parseInt(that.selectIndex)- 1;
		$('#' + that.companyTreeId).find('.jstree-search')[that.selectIndex-1].className = "jstree-anchor jstree-search jstree-searchCheck"
		$('#' + that.companyTreeId).find('.jstree-searchCheck')[1].className = "jstree-anchor jstree-search";

		let container = $('#' + that.companyTreeId).find('.vision_tree');
		let _this = $('#' + this.companyTreeId).find('.jstree-search').eq(that.selectIndex-1);
		let top = _this.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3;
		container.animate({ scrollTop: top });
	}
	downArrow(){
		var that = this;
		if(parseInt(this.selectIndex) == parseInt(this.selectCount)){
			that.jsonApiService.message("目前已经在结束位置");
			return;
		}
		let lenindex =  parseInt(this.selectIndex); 
		$('#' + this.companyTreeId).find('.jstree-searchCheck')[0].className = "jstree-anchor jstree-search "
		this.selectIndex = parseInt(this.selectIndex) + 1;
		$('#' + this.companyTreeId).find('.jstree-search')[lenindex].className = "jstree-anchor jstree-search jstree-searchCheck"

		let container = $('#' + that.companyTreeId).find('.vision_tree');
		let _this = $('#' + this.companyTreeId).find('.jstree-search').eq(lenindex);
		let top = _this.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3;
		container.animate({ scrollTop: top });
	}
	//拉取车辆数据
	select2Car() {
		var that = this;
		$("#carNumberSelect2").select2({
			language: "zh-CN",
			placeholder: "请选择",
			allowClear: true,
			minimumInputLength: 2, //最少2个字符，select2才显示查询的内容

			ajax: {
				url: config.BaseURL + that.sourceCarUrl,
				dataType: 'json',
				delay: 50,
				method: "POST",
				xhrFields: {
					withCredentials: true
				},
				data: function(params) {
					return {
						"carNumber": params.term, // search term
						"typeFlag": that.typeFlag
					};
				},
				processResults: function(data, params) {
					var options = new Array();
					// 小于10个数量才判断重复
					if(data.data.length<=10){
						let arr = []
						let sameCar = []
						// 判断相同的车牌号
						for (let index = 0; index < data.data.length; index++) {
							let car = data.data[index];
							if(arr.indexOf(car.carNumber)!=-1){
								sameCar.push(car.carNumber)
							}else{
								arr.push(car.carNumber);
							}
						}
						$(data.data).each(function(index, car) {
							if(sameCar.indexOf(car.carNumber)!=-1){
								options.push({
									id: car.deviceId,
									text: car.carNumber+"["+car.parentName+"]"
								})
							}else{
								options.push({
									id: car.deviceId,
									text: car.carNumber
								})
							}
						});
					}else{
						$(data.data).each(function(index, car) {
							options.push({
								id: car.deviceId,
								text: car.carNumber
							})
						});
					}
					return {
						results: options //获取查询后的结果
					};
				},
				cache: true
			},
			templateResult: this.formatRepo
		}).on("select2:select", function(e) {
			that.carClickFlag = true;
			that.clearKeyCodeEvent = true;
			var data = e.params.data;
			that.deviceId = data.id;
			if(data.text.indexOf('[') > 0){
                that.carNumber = data.text.split('[')[0];
            } else {
                that.carNumber = data.text;
            }
			that.sendParent();
			that.keyEvent();
			that.carClickFlag = false;
			let len = that.carList.length;
			if(len > 1 && that.deviceId) {
				for(let x = 0; x < len; x++) {
					if(that.carNumber == that.carList[x].text) {
						that.carIndexMsg = {
							allNums: len,
							index: (x + 1),
							status: true,
						}
						break;
					}
				}
			} else {
				that.carIndexMsg.status = false;
			}
		});
	}
	//select2 格式回调函数
	formatRepo(state) {
		if(!state.id) {
			return state.text;
		}
		var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	clearSelect2(obj) {
		obj.empty();
		obj.prepend("<option value=''>请选择</option>");
	}
	//擦除车牌号码所选值
	del_carNumber() {
		this.deviceId = '';
		this.carNumber = '';
		if(this.companyId) {
			this.queryCarListByCompanyId(this.companyId)
		} else {
			//采用简单粗暴的方法清除;官方推荐的方法失效
			var str = $("<span class='select2-selection__placeholder'>请选择</span>");
			$('#carNumberSelect2').val("");
			$("#select2-carNumberSelect2-container").empty();
			$("#select2-carNumberSelect2-container").attr("title", "");
			$("#select2-carNumberSelect2-container").prepend(str);
		}
		this.sendParent()
	}
	//公司id拉取车辆
	queryCarListByCompanyId(companyId) {
		this.deviceId = '';
		this.carNumber = '';
		this.isAllowNext = false;
		this.isAllowPre = false;
		this.carIndexMsg.status = false;
		let reqdata = 'companyId=' + companyId;
		this.jsonApiService.http("stats/carlist.html", reqdata).subscribe(data => {
			var carlist = data.data;
			var selectdata = [];
			for(var i = 0; i < carlist.length; i++) {
				var obj = {
					id: carlist[i].deviceId,
					text: carlist[i].carNumber,
				}
				selectdata[i] = obj;
			}
			this.carList = selectdata;
			var selectObj = $("#carNumberSelect2");
			this.clearSelect2(selectObj); //清除Select中的数据
			selectObj.select2({
				language: "zh-CN",
				data: selectdata, //为Select添加数据
				templateResult: this.formatRepo
			});
			if(this.companyData && this.companyData.deviceId){
              this.deviceId = this.companyData.deviceId;
              this.carNumber = this.companyData.carNumber;
              $('#carNumberSelect2').val(this.companyData.deviceId).trigger('change');
              this.sendParent();
          }
		})
	}
	//selcet2  车辆
	nextCar(type) {
		this.isAllowNext = false;
		this.isAllowPre = false;
		//		this.isDisable = true;
		if(this.carList.length > 1 && this.deviceId) {
			let len = this.carList.length;
			for(let i = 0; i < len; i++) {
				if(this.carList[i].text === this.carNumber && this.carList[i].id === this.deviceId) {
					if(type === 'pre') {
						if(i > 0) {

							this.carNumber = this.carList[i - 1].text;
							this.deviceId = this.carList[i - 1].id;
							$('#carNumberSelect2').val(this.deviceId).trigger('change');
							break;
						} else {
							this.isAllowPre = true;
							break;
						}
					} else if(type === 'next') {
						if(i < len - 1) {
							this.carNumber = this.carList[i + 1].text;
							this.deviceId = this.carList[i + 1].id;
							$('#carNumberSelect2').val(this.deviceId).trigger('change');
							break;
						} else {
							this.isAllowNext = true;
							break;
						}
					}
				}
			}
			for(let x = 0; x < len; x++) {
				if(this.carNumber == this.carList[x].text) {
					this.carIndexMsg = {
						allNums: len,
						index: (x + 1),
						status: true,
					}
					break;
				}

			}
		}
		this.sendParent()
	}
	//公司树模糊搜索	click
	companySearchBtn() {
		var that = this;
		var value = $('#' + this.companyTreeId).find('.treeSearchInput').val();
		$('#' + this.companyTreeId).find('.treeId').eq(0).jstree(true).search(value);
		let searchResult = $('#' + this.companyTreeId).find('.jstree-search').length;
		if(searchResult < 1) {
			that.jsonApiService.message('未搜索到结果');
			return;
		}
		$('#' + this.companyTreeId).find('.jstree-search').each(function(index, obj) {
			if(index < 1) { //js树搜索定位到结果的第一个地方；
				let container = $('#' + that.companyTreeId).find('.vision_tree');
				let scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({
					scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
				});
			}
		})
	}
}